import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
const login = () => import('@/pages/login/login')
const register = () => import('@/pages/register/register')
const layout = () => import('@/pages/index/layout')
const index = () => import('@/pages/index/index')
const category = () => import('@/pages/category/category')
const goodsList = () => import('@/pages/goods/goodsList')
const goodsinfo = () => import('@/pages/goods/goodsinfo')
const cart = () => import('@/pages/cart/cart')
const mine = () => import('@/pages/mine/mine')
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'index',
    component: layout,
    children: [
      { path: '', component: index },
      { path: 'category', component: category },
      { path: 'category/:sid', component: goodsList },
      { path: 'cart', component: cart },
      { path: 'mine', component: mine },
    ]
  },
  { path: '/goodsinfo/:id', component: goodsinfo },
  {
    path: '/login',
    name: 'login',
    component: login
  },
  {
    path: '/register',
    name: 'register',
    component: register
  },
  {
    path: '/about',
    name: 'About',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 解决:NavigationDuplicated: Avoided redundant navigation to current location.捕获错误
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}
router.beforeEach((to, from, next) => {
  // 判断路由
  if (to.path != '/cart') {
    // 登录页不做拦截
    next();
  } else {
    if (localStorage.getItem('userInfo')&&to.path == '/cart') {
      // localstorage有数据，说明已经登录过
      next()
    } else {
      // localstorage没有数据，说明没有登录，就去登录
      next()
      query: { redirect: to.fullPath }
    }
  }
})
export default router
